/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package graficotestearquivo;
import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.RefineryUtilities;
/**
 *
 * @author saulomedeiros
 */
public class LineChartDemo2 extends javax.swing.JFrame {
    private static int idparameter;
    /**
     * Creates new form LineChartDemo2
     */
    /**
     * Creates new form LineChartDemo2
     */
    public LineChartDemo2()
        {
                //super(s);
                JPanel jpanel = createDemoPanel();
                //jpanel.setPreferredSize(new Dimension(500, 270));
                setContentPane(jpanel);
        }
        public static int getIdparameter(){
            return LineChartDemo2.idparameter;
        }
        public static void InserirLinechart(String linhax, String linhay, int contlinha){// inserir no banco de dados
                PreparedStatement ps = null;
                Connection conn = null;
                Statement st = null;
                //int idparameter=0;
                Scanner teclado=new Scanner(System.in);
                try{
                     DriverManager.registerDriver(new com.mysql.jdbc.Driver());
                     conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbtuning", "root", "");
                     ps = conn.prepareStatement("insert into linechartdata (idparameter,idline,xvalues,yvalues) VALUES (?,?,?,?) ");
                     st=conn.createStatement();
                     ResultSet rs=st.executeQuery("select max(idparameter) from parameter");
                     while(rs.next()){
                        idparameter=rs.getInt(1);
                        
                     }
                                System.out.print("\nidparameter:");
                                ps.setInt(1, idparameter);
                                System.out.print("\nidline:");
                                ps.setInt(2, contlinha);
                                System.out.print("\nxvalues:");
                                ps.setString(3,linhax);
                                System.out.print("\nyvalues:");
                                ps.setString(4,linhay);
                                ps.executeUpdate();
                        
                 }catch(InputMismatchException e){
                     System.out.println(e.getMessage());
                 }catch(SQLException e){
                     System.out.println(e.getMessage());
                 }finally{
                    try {
                        ps.close();
                        conn.close();
                    } catch (SQLException ex) {
                        System.out.println(ex.getMessage());
                    }

                 }
        }
        public static Double[] LerTxT(String txt){
                int contlinha=0; 
                String linhax = null,linhay = null;
                String[] parts;
                //BufferedReader br=null;
                Double[] partsdouble= new Double[100];
                /*try {
                    br = new BufferedReader(new FileReader(txt)); 
                    StringBuilder sb = new StringBuilder();
                  
                    String line = br.readLine();
                    while (line != null) {
                        sb.append(line);
                        sb.append("\n");
                        line = br.readLine();
                    }*/
                    //System.out.println("o que eu queria:"+sb.toString());
                    try {  
			   File arquivo = new File(txt);  
			   FileInputStream   fileInputStream = new FileInputStream(arquivo);  
			   InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);  
			   LineNumberReader  lineNumberReader= new LineNumberReader(inputStreamReader);
                           StringBuilder sb = new StringBuilder();
			   String linha;  
			   

			   while(lineNumberReader.ready()) {  
                                   int ln = lineNumberReader.getLineNumber();
				   linha = lineNumberReader.readLine(); 
				   if( ln>=12 && ln<=31){
                                           sb.append(linha);
                                           if(ln%2==0){
                                               linhax=linha;
                                               System.out.println("linha x:"+linhax);}
                                           else
                                               linhay=linha;        
                                           if(ln%2!=0){
                                                contlinha++;
                                                InserirLinechart(linhax,linhay,contlinha);
                                           }//sb.append("\n");
					   System.out.println("linha-grafico de linhas:"+ln);
					   System.out.println(linha);  
				   }   
			   }
                           
                            String everything = sb.toString();
                            parts = everything.split(",");
                            for(int i=0;i<partsdouble.length;i++)
                              {
                                   partsdouble[i]=Double.parseDouble(parts[i]);
                              }
                 }catch(FileNotFoundException e){
                        System.out.println(e.getMessage());
                 }catch(IOException e){
                        System.out.println(e.getMessage());
                 } 
                /*finally {
                    try {
                        br.close();
                    } catch (IOException ex) {
                        System.out.println(ex.getMessage());
                    }

                }*/
         return partsdouble;
         }
       
        public static Double[] LerDoBanco(int qntelemento,int execution){
            int j=0;
            int w=50;
            int num;
            Double[] partsdouble=new Double[100];
            String[] parts;
            String[] part;
            try{    
                DriverManager.registerDriver(new com.mysql.jdbc.Driver());
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbtuning", "root", "");
		Statement st = conn.createStatement();
                num=LineChartDemo2.getIdparameter()-qntelemento+execution+1;
                System.out.println("subtracao linha:"+num);
		ResultSet rs = st.executeQuery("select * from linechartdata  where idparameter="+num);
		while(rs.next()){
                    String xvalue = rs.getString(4);
                    parts = xvalue.split(",");
                    String yvalue=rs.getString(5);
                    part = yvalue.split(",");
                        for(int i=0;i<parts.length;i++){
                            partsdouble[j]=Double.parseDouble(parts[i]);
                            partsdouble[w]=Double.parseDouble(part[i]);
                            j++;
                            w++;                           
                        }
		}
		st.close();
		conn.close();
              }catch(SQLException e){
                  e.printStackTrace();
              } 
            return partsdouble;
        }
        public static XYDataset createDataset(Double[] partsdouble) 
        {
               
                XYSeries xyseries = new XYSeries("Primeiro");
                xyseries.add(partsdouble[0], partsdouble[5]);
                xyseries.add(partsdouble[1], partsdouble[6]);
                xyseries.add(partsdouble[2], partsdouble[7]);
                xyseries.add(partsdouble[3], partsdouble[8]);
                xyseries.add(partsdouble[4], partsdouble[9]);
                
                XYSeries xyseries1 = new XYSeries("Segundo");
                xyseries1.add(partsdouble[10],partsdouble[15]);
                xyseries1.add(partsdouble[11],partsdouble[16]);
                xyseries1.add(partsdouble[12],partsdouble[17]);
                xyseries1.add(partsdouble[13], partsdouble[18]);
                xyseries1.add(partsdouble[14], partsdouble[19]);
                
                XYSeries xyseries2 = new XYSeries("Terceiro");
                xyseries2.add(partsdouble[20],partsdouble[25]);
                xyseries2.add(partsdouble[21],partsdouble[26]);
                xyseries2.add(partsdouble[22],partsdouble[27]);
                xyseries2.add(partsdouble[23], partsdouble[28]);
                xyseries2.add(partsdouble[24], partsdouble[29]);
               
                XYSeries xyseries3 = new XYSeries("Quarto");
                xyseries3.add(partsdouble[30],partsdouble[35]);
                xyseries3.add(partsdouble[31],partsdouble[36]);
                xyseries3.add(partsdouble[32],partsdouble[37]);
                xyseries3.add(partsdouble[33], partsdouble[38]);
                xyseries3.add(partsdouble[34], partsdouble[39]);
                
                XYSeries xyseries4 = new XYSeries("Quinto");
                xyseries4.add(partsdouble[40],partsdouble[45]);
                xyseries4.add(partsdouble[41],partsdouble[46]);
                xyseries4.add(partsdouble[42],partsdouble[47]);
                xyseries4.add(partsdouble[43], partsdouble[48]);
                xyseries4.add(partsdouble[44], partsdouble[49]);
                
                XYSeries xyseries5 = new XYSeries("Sexto");
                xyseries5.add(partsdouble[50],partsdouble[55]);
                xyseries5.add(partsdouble[51],partsdouble[56]);
                xyseries5.add(partsdouble[52],partsdouble[57]);
                xyseries5.add(partsdouble[53], partsdouble[58]);
                xyseries5.add(partsdouble[54], partsdouble[59]);
                
                XYSeries xyseries6 = new XYSeries("Sétimo");
                xyseries6.add(partsdouble[60],partsdouble[65]);
                xyseries6.add(partsdouble[61],partsdouble[66]);
                xyseries6.add(partsdouble[62],partsdouble[67]);
                xyseries6.add(partsdouble[63], partsdouble[68]);
                xyseries6.add(partsdouble[64], partsdouble[69]);
                
                XYSeries xyseries7 = new XYSeries("Oitavo");
                xyseries7.add(partsdouble[70],partsdouble[75]);
                xyseries7.add(partsdouble[71],partsdouble[76]);
                xyseries7.add(partsdouble[72],partsdouble[77]);
                xyseries7.add(partsdouble[73], partsdouble[78]);
                xyseries7.add(partsdouble[74], partsdouble[79]);
                
                XYSeries xyseries8 = new XYSeries("Nono");
                xyseries8.add(partsdouble[80],partsdouble[85]);
                xyseries8.add(partsdouble[81],partsdouble[86]);
                xyseries8.add(partsdouble[82],partsdouble[87]);
                xyseries8.add(partsdouble[83], partsdouble[88]);
                xyseries8.add(partsdouble[84], partsdouble[89]);
                
                XYSeries xyseries9 = new XYSeries("Décimo");
                xyseries9.add(partsdouble[90],partsdouble[95]);
                xyseries9.add(partsdouble[91],partsdouble[96]);
                xyseries9.add(partsdouble[92],partsdouble[97]);
                xyseries9.add(partsdouble[93], partsdouble[98]);
                xyseries9.add(partsdouble[94], partsdouble[99]);
                
                XYSeriesCollection xyseriescollection = new XYSeriesCollection();
                xyseriescollection.addSeries(xyseries);
                xyseriescollection.addSeries(xyseries1);
                xyseriescollection.addSeries(xyseries2);
                xyseriescollection.addSeries(xyseries3);
                xyseriescollection.addSeries(xyseries4);
                xyseriescollection.addSeries(xyseries5);
                xyseriescollection.addSeries(xyseries6);
                xyseriescollection.addSeries(xyseries7);
                xyseriescollection.addSeries(xyseries8);
                xyseriescollection.addSeries(xyseries9);
                return xyseriescollection;
        }
        public static XYDataset createDataset2(Double[] partsdouble) 
        {
               
                XYSeries xyseries = new XYSeries("Primeiro");
                xyseries.add(partsdouble[0], partsdouble[50]);
                xyseries.add(partsdouble[1], partsdouble[51]);
                xyseries.add(partsdouble[2], partsdouble[52]);
                xyseries.add(partsdouble[3], partsdouble[53]);
                xyseries.add(partsdouble[4], partsdouble[54]);
                
                XYSeries xyseries1 = new XYSeries("Segundo");
                xyseries1.add(partsdouble[5],partsdouble[55]);
                xyseries1.add(partsdouble[6],partsdouble[56]);
                xyseries1.add(partsdouble[7],partsdouble[57]);
                xyseries1.add(partsdouble[8], partsdouble[58]);
                xyseries1.add(partsdouble[9], partsdouble[59]);
                
                XYSeries xyseries2 = new XYSeries("Terceiro");
                xyseries2.add(partsdouble[10],partsdouble[60]);
                xyseries2.add(partsdouble[11],partsdouble[61]);
                xyseries2.add(partsdouble[12],partsdouble[62]);
                xyseries2.add(partsdouble[13], partsdouble[63]);
                xyseries2.add(partsdouble[14], partsdouble[64]);
               
                XYSeries xyseries3 = new XYSeries("Quarto");
                xyseries3.add(partsdouble[15],partsdouble[65]);
                xyseries3.add(partsdouble[16],partsdouble[66]);
                xyseries3.add(partsdouble[17],partsdouble[67]);
                xyseries3.add(partsdouble[18], partsdouble[68]);
                xyseries3.add(partsdouble[19], partsdouble[69]);
                
                XYSeries xyseries4 = new XYSeries("Quinto");
                xyseries4.add(partsdouble[20],partsdouble[70]);
                xyseries4.add(partsdouble[21],partsdouble[71]);
                xyseries4.add(partsdouble[22],partsdouble[72]);
                xyseries4.add(partsdouble[23], partsdouble[73]);
                xyseries4.add(partsdouble[24], partsdouble[74]);
                
                XYSeries xyseries5 = new XYSeries("Sexto");
                xyseries5.add(partsdouble[25],partsdouble[75]);
                xyseries5.add(partsdouble[26],partsdouble[76]);
                xyseries5.add(partsdouble[27],partsdouble[77]);
                xyseries5.add(partsdouble[28], partsdouble[78]);
                xyseries5.add(partsdouble[29], partsdouble[79]);
                
                XYSeries xyseries6 = new XYSeries("Sétimo");
                xyseries6.add(partsdouble[30],partsdouble[80]);
                xyseries6.add(partsdouble[31],partsdouble[81]);
                xyseries6.add(partsdouble[32],partsdouble[82]);
                xyseries6.add(partsdouble[33], partsdouble[83]);
                xyseries6.add(partsdouble[34], partsdouble[84]);
                
                XYSeries xyseries7 = new XYSeries("Oitavo");
                xyseries7.add(partsdouble[35],partsdouble[85]);
                xyseries7.add(partsdouble[36],partsdouble[86]);
                xyseries7.add(partsdouble[37],partsdouble[87]);
                xyseries7.add(partsdouble[38], partsdouble[88]);
                xyseries7.add(partsdouble[39], partsdouble[89]);
                
                XYSeries xyseries8 = new XYSeries("Nono");
                xyseries8.add(partsdouble[40],partsdouble[90]);
                xyseries8.add(partsdouble[41],partsdouble[91]);
                xyseries8.add(partsdouble[42],partsdouble[92]);
                xyseries8.add(partsdouble[43], partsdouble[93]);
                xyseries8.add(partsdouble[44], partsdouble[94]);
                
                XYSeries xyseries9 = new XYSeries("Décimo");
                xyseries9.add(partsdouble[45],partsdouble[95]);
                xyseries9.add(partsdouble[46],partsdouble[96]);
                xyseries9.add(partsdouble[47],partsdouble[97]);
                xyseries9.add(partsdouble[48], partsdouble[98]);
                xyseries9.add(partsdouble[49], partsdouble[99]);
                
                XYSeriesCollection xyseriescollection = new XYSeriesCollection();
                xyseriescollection.addSeries(xyseries);
                xyseriescollection.addSeries(xyseries1);
                xyseriescollection.addSeries(xyseries2);
                xyseriescollection.addSeries(xyseries3);
                xyseriescollection.addSeries(xyseries4);
                xyseriescollection.addSeries(xyseries5);
                xyseriescollection.addSeries(xyseries6);
                xyseriescollection.addSeries(xyseries7);
                xyseriescollection.addSeries(xyseries8);
                xyseriescollection.addSeries(xyseries9);
                return xyseriescollection;
        }

        public static JFreeChart createChart(XYDataset xydataset)
        {
                JFreeChart jfreechart = ChartFactory.createXYLineChart("#Write Operations", "Database Size (#pages) log scale", "#Write operation (log scale)", xydataset, PlotOrientation.VERTICAL, true, true, false);
                XYPlot xyplot = (XYPlot)jfreechart.getPlot();
                xyplot.setDomainPannable(true);
                xyplot.setRangePannable(true);
                XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer)xyplot.getRenderer();
                xylineandshaperenderer.setBaseShapesVisible(true);
                xylineandshaperenderer.setBaseShapesFilled(true);
                NumberAxis numberaxis = (NumberAxis)xyplot.getRangeAxis();
                numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
                return jfreechart;
        }
        //@OverWrite
        public static JPanel createDemoPanel(int num1,int numero){     
                JFreeChart jfreechart = createChart(createDataset2(LerDoBanco(num1,numero)));
                ChartPanel chartpanel = new ChartPanel(jfreechart);
                chartpanel.setMouseWheelEnabled(true);
                return chartpanel;
          
            
        }
        public static JPanel createDemoPanel()
        {
                //Scanner teclado=new Scanner(System.in);
                //System.out.println("digite o nome do arquivo:");
                JFreeChart jfreechart = createChart(createDataset(LerTxT("arquivo01.txt")));
                ChartPanel chartpanel = new ChartPanel(jfreechart);
                chartpanel.setMouseWheelEnabled(true);
                return chartpanel;
        }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LineChartDemo2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LineChartDemo2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LineChartDemo2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LineChartDemo2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LineChartDemo2().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
